<?php
$GALLERY_URL = XOOPS_ROOT_PATH . '/modules/xoopsgallery/';
global $gallery;
require_once($GALLERY_URL.'config.php');

if (!$gallery->app->skip_permission_checks) {
	require_once($GALLERY_URL.'init_basic.php');
}


function b_xoopsgallery_getImages($numImages, $maxSize, $imageCriteria, $rand, $sort='', $sortOrder='DESC') {

	global $gallery;

	// Debug
    $debug_info = "XoopsGallery block getImages function information \n  numImages: $numImages \n  maxSize: $maxSize \n  imageCriteria: $imageCriteria \n  rand: $rand \n  sort: $sort \n  sortOrder: $sortOrder \n  gallery->config['blockAlbumMode']:  " . $gallery->config['blockAlbumMode'] . " \n";
	
	// Image selection
	$image_handler =& xoops_getmodulehandler('image', 'xoopsgallery');
	$criteria = new CriteriaCompo(new Criteria('image_type', 'original'));
	if ($imageCriteria != '') {
		$criteria->add($imageCriteria);
	}

	// Admin global preference on albums for block use
	global $XOOPSGALLERY_moduleConfig;

	if($gallery->config['blockAlbumMode'] != 'AllAlbums' && strlen($gallery->config['blockAlbumList']) > 0) {
		$blockAlbumArry=preg_split('/[;,]/', $gallery->config['blockAlbumList']);

		switch($gallery->config['blockAlbumMode']){
			case 'AllExcept': 
				$sqlComp = 'AND';
				$sqlLike = 'NOT LIKE';
				$sqlEquality = '<>';
				break;
			case 'SelectedAlbums': 
			default:
				$sqlComp = 'OR';
				$sqlLike = 'LIKE';
				$sqlEquality = '=';
				break;
		}

		$blockAlbumCritera = new CriteriaCompo();
		foreach ($blockAlbumArry as $albumName){
			if (strpos($albumName, '%') === false && strpos($albumName, '_') === false) {
			    // no wildcards, use =, <>
				$blockAlbumCritera->add(new Criteria('image_albumdir', $albumName, $sqlEquality), $sqlComp);
			} else {
				// wildcards, use LIKE, NOT LIKE
				$blockAlbumCritera->add(new Criteria('image_albumdir', $albumName, $sqlLike), $sqlComp);
			}
		}
		$criteria->add($blockAlbumCritera);
	}

	// Order
	if ($rand) {
		$criteria->setSort('Rand()');
	} elseif ($sort != '') {
		$criteria->setSort($sort);
		$criteria->setOrder($sortOrder); 
	}

	// Collect 10* the number of random images that are to be shown...
	// this way we can make sure there is a thumbnail for all of the images put into the block.
	$overLimit = 10*$numImages;
	$criteria->setLimit($overLimit);
	$images =& $image_handler->getObjects($criteria, true);
	$block = array();
	$maxW = 0;
	$maxH = 0;

	$debug_info .= "  criteria: " . $criteria->renderWhere() . " \n";
	$debug_info .= "  result images: " . count($images) . " \n";

	if (!$gallery->app->skip_permission_checks) {
		$chkAlbum = new Album();
	}
	foreach (array_keys($images) as $i) {
		$debug_info .= "\n  image: $i \n";

		if (!($images[$i]->ThumbExists())) { 
			$debug_info .= "    No thumb exists. \n";
			continue; 
		} // no thumbnail for this picture so go to the next...

		$debug_info .= "    Thumb path: " . $images[$i]->getFullThumbPath() . " \n";
		$debug_info .= "    Skip permission checks: " . $gallery->app->skip_permission_checks . " \n";
		$debug_info .= "    Album dir: " . $images[$i]->getVar('image_albumdir') . " \n";
		$debug_info .= "    Image name: " . $images[$i]->getVar('image_name') . " \n";	
		
		if (!$gallery->app->skip_permission_checks) {
			// Get photo object from Gallery and check permissions
			$chkAlbum->load($images[$i]->getVar('image_albumdir'));
			if (!$gallery->user->canReadAlbum($chkAlbum)) { 
				$debug_info .= "    User can't read album. \n";
				continue;
			}
			$chkIndex = $chkAlbum->getPhotoIndex($images[$i]->getVar('image_name'));
			$chkPhoto =& $chkAlbum->getPhoto($chkIndex);
			if ($chkIndex < 0) {
				$debug_info .= "    Photo doesn't exist in album!  Need to check why! \n";   
				continue;
			}
			if ($chkPhoto->isHidden()) {
				$debug_info .= "    Photo is hidden. \n";
				continue;
			}
		}
		
		// Add this image to the block's list of images if it is a valid image
		if ($hw = getimagesize($images[$i]->getFullThumbPath())) {
			$debug_info .= "    hw: $hw[0] x $hw[1] \n";
		
			// Limit size of image
			if (intval($maxSize) < $hw[0]) {
				$image['width'] = intval($maxSize);
				$image['height'] = $hw[1] * ($image['width'] / $hw[0]);
			} else {
				$image['width'] = $hw[0];
				$image['height'] = $hw[1];
			}
			
			// Check max height and width
			if ($image['width'] > $maxW) {
				$maxW = $image['width'];
			}
			if ($image['height'] > $maxH) {
				$maxH = $image['height'];
			}

			// Get links to image
			// NOTE:  This can be ONLY be refactored to use the Gallery API instead 
			// of re-working the URLs here IF the user has permission checks enabled!
			$image['src'] = $images[$i]->getFullThumbUrl();
			$image['link'] = XOOPS_URL.'/modules/xoopsgallery/view_photo.php?xoops_imageid='.$images[$i]->getVar('image_id').'&amp;set_albumName='.$images[$i]->getVar('image_albumdir').'&amp;id='.$images[$i]->getVar('image_name');
			$image['created'] = formatTimestamp($images[$i]->getVar('image_created'), 's');
			$image['resizedURL'] = $images[$i]->getSizedURL();
			$image['fullURL'] = $images[$i]->getFullURL();
			$block['images'][] =& $image;
			unset($image);

			if (count($block['images']) >= $numImages) { break; };
		}
		$debug_info .= " \n";
	}
	$debug_info .= " \n\n";
	unset($images);
	unset($chkAlbum);
	unset($criteria);
	
	// Store max H and W, set default option values (overriden by specific block handlers)
	$block['imageWidth'] = $maxW;
	$block['imageHeight'] = $maxH;
	$block['showCreated'] = false;
	$block['format'] = 'narrow';

	// Debug
	if ($gallery->app->debug == _YES) {
		$block['debug_info'] = $debug_info;
	}
	unset($debug_info);
	return $block;
}

function b_xoopsgallery_newshow($options){
	$criteria = '';
	$block = b_xoopsgallery_getImages($options[0], $options[1], $criteria, false, 'image_created', 'DESC');
	
	// Handle block options
	$block['showCreated'] = (!empty($options[2]));
	$block['format'] = $options[3];

	return $block;
}

function b_xoopsgallery_newedit($options) {
	$form = _MB_GALLERY_DISP."&nbsp;";
	$form .= '<input type="text" name="options[0]" value="'.intval($options[0]).'" />';
	$form .= '<br />'._MB_GALLERY_MAXW.'&nbsp;<input type="text" name="options[1]" value="'.$options[1].'" />';
	$form .= '<br />'._MB_GALLERY_SHOWDATE.'&nbsp;<input type="radio" name="options[2]" value="1"';
	if ( !isset($options[2]) || $options[2]==1 ) {$form .= ' checked="checked"';}
	$form .= ' />'._MB_GALLERY_YES.'&nbsp;<input type="radio" name="options[2]" value="0"';
	if ($options[2]==0) {$form .= ' checked="checked"';}
	$form .= ' />'._MB_GALLERY_NO.'&nbsp;'; 
	$form .= '<br />'._MB_GALLERY_FORMAT.'&nbsp;<select name="options[3]">';
	$form .= '<option value="narrow"';
	if ($options[3] == "narrow") {
		$form .= ' selected="selected"';
	}
	$form .= '>'._MB_GALLERY_FORMATNARROW.'</option>';
	$form .= '<option value="wide"';
	if ($options[3] == "wide") {
		$form .= ' selected="selected"';
	}
	$form .= '>'._MB_GALLERY_FORMATWIDE.'</option>';
	$form .= '</select>';
	return $form;
}

function b_xoopsgallery_random_recentshow($options){
	$curTime = time();
	$days = $options[4];
	if ($days <= 0) $days = 30;
	$delta = $days*86400;
	$cutoff = $curTime - $delta;

	$criteria = new Criteria('image_created',$cutoff,">=" );
	
	$block = b_xoopsgallery_getImages($options[0], $options[1], $criteria, true);
	
	// Handle block options
	$block['showCreated'] = (!empty($options[2]));
	$block['format'] = $options[3];

	return $block;
}

function b_xoopsgallery_random_recentedit($options) {
	$form = _MB_GALLERY_DISP."&nbsp;";
	$form .= '<input type="text" name="options[0]" value="'.intval($options[0]).'" />';
	$form .= '<br />'._MB_GALLERY_MAXW.'&nbsp;<input type="text" name="options[1]" value="'.$options[1].'" />';
	$form .= '<br />'._MB_GALLERY_SHOWDATE.'&nbsp;<input type="radio" name="options[2]" value="1"';
	if ( !isset($options[2]) || $options[2]==1 ) {$form .= ' checked="checked"';}
	$form .= ' />'._MB_GALLERY_YES.'&nbsp;<input type="radio" name="options[2]" value="0"';
	if ($options[2]==0) {$form .= ' checked="checked"';}
	$form .= ' />'._MB_GALLERY_NO.'&nbsp;'; 
	$form .= '<br />'._MB_GALLERY_FORMAT.'&nbsp;<select name="options[3]">';
	$form .= '<option value="narrow"';
	if ($options[3] == "narrow") {
		$form .= ' selected="selected"';
	}
	$form .= '>'._MB_GALLERY_FORMATNARROW.'</option>';
	$form .= '<option value="wide"';
	if ($options[3] == "wide") {
		$form .= ' selected="selected"';
	}
	$form .= '>'._MB_GALLERY_FORMATWIDE.'</option>';
	$form .= '</select>';
	$form .= '<br />'._MB_GALLERY_HISTORYDESC.'&nbsp;';
	$form .= '<br />'._MB_GALLERY_HISTORYDAYS.'&nbsp;<input type="text" name="options[4]" value="'.$options[4].'" />';
	return $form;
}

function b_xoopsgallery_getRandomImage($options) {
	$criteria = '';
	$block = b_xoopsgallery_getImages($options[0], $options[1], $criteria, true);
	
	// Handle block options
	$block['showCreated'] = (!empty($options[2]));
	$block['format'] = $options[3];

	return $block;
}

function b_xoopsgallery_editRandomImage($options) {
	$form = _MB_GALLERY_DISP."&nbsp;";
	$form .= '<input type="text" name="options[0]" value="'.intval($options[0]).'" />';
	$form .= '<br />'._MB_GALLERY_MAXW.'&nbsp;<input type="text" name="options[1]" value="'.$options[1].'" />';
	$form .= '<br />'._MB_GALLERY_SHOWDATE.'&nbsp;<input type="radio" name="options[2]" value="1"';
	if ( !isset($options[2]) || $options[2]==1 ) {$form .= ' checked="checked"';}
	$form .= ' />'._MB_GALLERY_YES.'&nbsp;<input type="radio" name="options[2]" value="0"';
	if ($options[2]==0) {$form .= ' checked="checked"';}
	$form .= ' />'._MB_GALLERY_NO.'&nbsp;'; 
	$form .= '<br />'._MB_GALLERY_FORMAT.'&nbsp;<select name="options[3]">';
	$form .= '<option value="narrow"';
	if ($options[3] == "narrow") {
		$form .= ' selected="selected"';
	}
	$form .= '>'._MB_GALLERY_FORMATNARROW.'</option>';
	$form .= '<option value="wide"';
	if ($options[3] == "wide") {
		$form .= ' selected="selected"';
	}
	$form .= '>'._MB_GALLERY_FORMATWIDE.'</option>';
	$form .= '</select>';
	return $form;
}
?>
